import { openApiCheck } from '@mintlify/common';
import { readFile } from 'fs/promises';
import yaml from 'js-yaml';
import * as path from 'path';
import { getFileList } from '../fs/index.js';
import { getFileExtension } from '../utils.js';
export const categorizeFiles = async (contentDirectoryPath) => {
    const allFilesInCmdExecutionPath = getFileList(contentDirectoryPath);
    const contentFilenames = [];
    const staticFilenames = [];
    const openApiFiles = [];
    const snippets = [];
    const snippetsV2 = [];
    for await (const filename of allFilesInCmdExecutionPath) {
        const extension = getFileExtension(filename);
        switch (extension) {
            case 'mdx':
            case 'md':
                if (filename.startsWith('/_snippets/')) {
                    snippets.push(filename);
                    break;
                }
                if (filename.startsWith('/snippets/')) {
                    snippetsV2.push(filename);
                    break;
                }
                contentFilenames.push(filename);
                break;
            case 'json':
            case 'yaml':
            case 'yml':
                try {
                    // we need to read from the fs so we can store the original spec
                    const str = await readFile(path.join(contentDirectoryPath, filename), 'utf8');
                    const obj = extension === 'json' ? JSON.parse(str) : yaml.load(str);
                    // openApiCheck modifies the spec in place - copy before
                    if (!(await openApiCheck(structuredClone(obj))))
                        break;
                    const fileName = path.parse(filename).base;
                    openApiFiles.push({
                        filename: fileName.substring(0, fileName.lastIndexOf('.')),
                        spec: obj,
                    });
                }
                catch { } // not an openapi spec
                break;
            default:
                staticFilenames.push(filename);
        }
    }
    return { contentFilenames, staticFilenames, openApiFiles, snippets, snippetsV2 };
};
